<template>
  <div class="window-container">
    <div class="page-header">
      <h2 class="page-title">窗口管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateWindow">
          <el-icon><Plus /></el-icon>新建窗口
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索过滤器 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="窗口名称">
          <el-input v-model="filterForm.name" placeholder="请输入窗口名称" clearable />
        </el-form-item>
        <el-form-item label="位置">
          <el-input v-model="filterForm.location" placeholder="请输入位置" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 窗口表格 -->
    <div class="window-table">
      <el-table
        :data="windowList"
        style="width: 100%"
        v-loading="tableLoading"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="窗口名称" min-width="120" />
        <el-table-column prop="location" label="位置" min-width="150" />
        <el-table-column label="服务类型" min-width="200">
          <template #default="scope">
            <el-tag
              v-for="(type, index) in scope.row.serviceTypeNames"
              :key="index"
              size="small"
              class="service-type-tag"
            >
              {{ type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEditWindow(scope.row)">编辑</el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDeleteWindow(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新建/编辑窗口对话框 -->
    <el-dialog
      v-model="windowDialog.visible"
      :title="windowDialog.isEdit ? '编辑窗口' : '新建窗口'"
      width="600px"
    >
      <el-form
        ref="windowFormRef"
        :model="windowForm"
        :rules="windowRules"
        label-width="100px"
      >
        <el-form-item label="窗口名称" prop="name">
          <el-input v-model="windowForm.name" placeholder="请输入窗口名称" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="windowForm.location" placeholder="请输入窗口位置" />
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceTypeIds">
          <el-select
            v-model="windowForm.serviceTypeIds"
            multiple
            collapse-tags
            style="width: 100%"
            placeholder="请选择服务类型"
          >
            <el-option
              v-for="item in serviceTypes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="windowForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="windowDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitWindowForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'

// 窗口列表数据 - 模拟数据
const windowList = ref([
  {
    id: 1,
    name: '个人业务窗口1',
    location: '一楼大厅',
    serviceTypeIds: [1, 2],
    serviceTypeNames: ['个人业务', '信贷业务'],
    status: 1,
    createTime: '2023-06-01 09:00:00'
  },
  {
    id: 2,
    name: '企业业务窗口',
    location: '一楼东侧',
    serviceTypeIds: [3],
    serviceTypeNames: ['企业业务'],
    status: 1,
    createTime: '2023-06-01 09:00:00'
  },
  {
    id: 3,
    name: 'VIP业务窗口',
    location: '二楼贵宾室',
    serviceTypeIds: [1, 3, 4],
    serviceTypeNames: ['个人业务', '企业业务', '理财业务'],
    status: 1,
    createTime: '2023-06-01 09:00:00'
  },
  {
    id: 4,
    name: '理财业务窗口',
    location: '一楼西侧',
    serviceTypeIds: [4],
    serviceTypeNames: ['理财业务'],
    status: 1,
    createTime: '2023-06-01 09:00:00'
  },
  {
    id: 5,
    name: '外汇业务窗口',
    location: '二楼西侧',
    serviceTypeIds: [5],
    serviceTypeNames: ['外汇业务'],
    status: 0,
    createTime: '2023-06-01 09:00:00'
  }
])

const tableLoading = ref(false)

// 业务类型列表 - 模拟数据
const serviceTypes = ref([
  { id: 1, name: '个人业务' },
  { id: 2, name: '信贷业务' },
  { id: 3, name: '企业业务' },
  { id: 4, name: '理财业务' },
  { id: 5, name: '外汇业务' }
])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 5 // 与模拟数据长度一致
})

// 过滤表单
const filterForm = reactive({
  name: '',
  location: '',
  status: ''
})

// 窗口对话框
const windowDialog = reactive({
  visible: false,
  isEdit: false
})

// 窗口表单
const windowFormRef = ref(null)
const windowForm = reactive({
  id: null,
  name: '',
  location: '',
  serviceTypeIds: [],
  status: 1
})

// 窗口表单规则
const windowRules = {
  name: [
    { required: true, message: '请输入窗口名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入位置', trigger: 'blur' }
  ],
  serviceTypeIds: [
    { required: true, type: 'array', message: '请选择服务类型', trigger: 'change' }
  ]
}

// 处理搜索
const handleSearch = () => {
  tableLoading.value = true

  // 使用模拟搜索
  setTimeout(() => {
    let filteredList = [...windowList.value]

    // 按名称筛选
    if (filterForm.name) {
      filteredList = filteredList.filter(window =>
        window.name.toLowerCase().includes(filterForm.name.toLowerCase())
      )
    }

    // 按位置筛选
    if (filterForm.location) {
      filteredList = filteredList.filter(window =>
        window.location.toLowerCase().includes(filterForm.location.toLowerCase())
      )
    }

    // 按状态筛选
    if (filterForm.status !== '') {
      filteredList = filteredList.filter(window =>
        window.status === filterForm.status
      )
    }

    windowList.value = filteredList
    pagination.total = filteredList.length
    tableLoading.value = false
  }, 500)
}

// 重置过滤器
const resetFilter = () => {
  filterForm.name = ''
  filterForm.location = ''
  filterForm.status = ''
  handleRefresh()
}

// 处理刷新
const handleRefresh = () => {
  tableLoading.value = true

  // 模拟刷新操作
  setTimeout(() => {
    // 重置为初始模拟数据
    windowList.value = [
      {
        id: 1,
        name: '个人业务窗口1',
        location: '一楼大厅',
        serviceTypeIds: [1, 2],
        serviceTypeNames: ['个人业务', '信贷业务'],
        status: 1,
        createTime: '2023-06-01 09:00:00'
      },
      {
        id: 2,
        name: '企业业务窗口',
        location: '一楼东侧',
        serviceTypeIds: [3],
        serviceTypeNames: ['企业业务'],
        status: 1,
        createTime: '2023-06-01 09:00:00'
      },
      {
        id: 3,
        name: 'VIP业务窗口',
        location: '二楼贵宾室',
        serviceTypeIds: [1, 3, 4],
        serviceTypeNames: ['个人业务', '企业业务', '理财业务'],
        status: 1,
        createTime: '2023-06-01 09:00:00'
      },
      {
        id: 4,
        name: '理财业务窗口',
        location: '一楼西侧',
        serviceTypeIds: [4],
        serviceTypeNames: ['理财业务'],
        status: 1,
        createTime: '2023-06-01 09:00:00'
      },
      {
        id: 5,
        name: '外汇业务窗口',
        location: '二楼西侧',
        serviceTypeIds: [5],
        serviceTypeNames: ['外汇业务'],
        status: 0,
        createTime: '2023-06-01 09:00:00'
      }
    ]

    pagination.total = windowList.value.length
    tableLoading.value = false
    ElMessage.success('数据已刷新')
  }, 500)
}

// 处理页码变化
const handleCurrentChange = (currentPage) => {
  pagination.currentPage = currentPage
}

// 处理每页条数变化
const handleSizeChange = (pageSize) => {
  pagination.pageSize = pageSize
  pagination.currentPage = 1
}

// 处理创建窗口
const handleCreateWindow = () => {
  // 重置表单
  Object.assign(windowForm, {
    id: null,
    name: '',
    location: '',
    serviceTypeIds: [],
    status: 1
  })

  windowDialog.isEdit = false
  windowDialog.visible = true
}

// 处理编辑窗口
const handleEditWindow = (row) => {
  // 填充表单
  Object.assign(windowForm, {
    id: row.id,
    name: row.name,
    location: row.location,
    serviceTypeIds: row.serviceTypeIds,
    status: row.status
  })

  windowDialog.isEdit = true
  windowDialog.visible = true
}

// 处理删除窗口
const handleDeleteWindow = (row) => {
  ElMessageBox.confirm(
    `确认删除窗口 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除操作
    windowList.value = windowList.value.filter(window => window.id !== row.id)
    pagination.total = windowList.value.length

    ElMessage.success('窗口删除成功')
  }).catch(() => {
    // 取消删除操作
  })
}

// 处理窗口状态切换
const handleToggleStatus = (row) => {
  const action = row.status === 1 ? '禁用' : '启用'

  ElMessageBox.confirm(
    `确认${action}窗口 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟状态切换操作
    const window = windowList.value.find(window => window.id === row.id)
    if (window) {
      window.status = window.status === 1 ? 0 : 1
      ElMessage.success(`窗口已${action}`)
    }
  }).catch(() => {
    // 取消操作
  })
}

// 提交窗口表单
const submitWindowForm = () => {
  windowFormRef.value.validate((valid) => {
    if (valid) {
      if (windowDialog.isEdit) {
        // 模拟编辑操作
        const index = windowList.value.findIndex(window => window.id === windowForm.id)
        if (index !== -1) {
          // 获取选择的服务类型名称
          const serviceTypeNames = windowForm.serviceTypeIds.map(id => {
            const serviceType = serviceTypes.value.find(type => type.id === id)
            return serviceType ? serviceType.name : ''
          }).filter(Boolean)

          // 更新窗口数据
          windowList.value[index] = {
            ...windowList.value[index],
            name: windowForm.name,
            location: windowForm.location,
            serviceTypeIds: [...windowForm.serviceTypeIds],
            serviceTypeNames: serviceTypeNames,
            status: windowForm.status
          }

          ElMessage.success('窗口更新成功')
        }
      } else {
        // 模拟创建操作
        // 获取选择的服务类型名称
        const serviceTypeNames = windowForm.serviceTypeIds.map(id => {
          const serviceType = serviceTypes.value.find(type => type.id === id)
          return serviceType ? serviceType.name : ''
        }).filter(Boolean)

        // 创建新窗口
        const newWindow = {
          id: Math.max(...windowList.value.map(w => w.id)) + 1,
          name: windowForm.name,
          location: windowForm.location,
          serviceTypeIds: [...windowForm.serviceTypeIds],
          serviceTypeNames: serviceTypeNames,
          status: windowForm.status,
          createTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
        }

        windowList.value.push(newWindow)
        pagination.total = windowList.value.length

        ElMessage.success('窗口创建成功')
      }

      // 关闭对话框
      windowDialog.visible = false
    }
  })
}

// 初始化
onMounted(() => {
  // 在实际应用中，这里会从API加载数据
  // 现在使用的是模拟数据，所以不需要加载
})
</script>

<style scoped>
.window-container {
  padding: 15px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.window-table {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.service-type-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}
</style>
